import { Injectable } from "@nestjs/common";
import { EquipmentBaseService } from "../services/equipment-base.service";
import { CharacterService } from "../services/character.service";
import { CharacterEquipmentInventoryService } from "../services/character-equipment-inventory.service";
import { GemService } from "../services/gem.service";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository, DataSource } from "typeorm";
import { CharacterResourcesEntity } from "../entities/character-resources.entity";

@Injectable()
export class EquipmentWsHandlers {
  constructor(
    private readonly equipmentBaseService: EquipmentBaseService,
    private readonly characterService: CharacterService,
    private readonly characterEquipmentInventoryService: CharacterEquipmentInventoryService,
    private readonly gemService: GemService,
    @InjectRepository(CharacterResourcesEntity)
    private readonly characterResourcesRepository: Repository<CharacterResourcesEntity>,
    private readonly dataSource: DataSource
  ) { }

  /**
   * 装备商店列表查询 (1301)
   */
  async handleEquipmentShopList(data: any) {
    try {
      const { type = 2, base = 0, pageNum = 0 } = data;

      // 调用装备基础服务获取装备商店列表
      const result = await this.equipmentBaseService.getEquipmentShopList(
        type,
        base,
        pageNum,
        20 // 每页20条记录
      );

      return {
        act_id: 1301,
        code: 0,
        list: result.list,
        page: result.page,
        total: result.total,
      };
    } catch (error: any) {
      console.error("处理装备商店列表查询指令1301失败:", error);
      return {
        act_id: 1301,
        code: -1,
        msg: error?.message || "查询装备商店列表失败",
        list: [],
      };
    }
  }

  /**
   * 银币购买装备 (1302)
   */
  async handlePurchaseEquipmentWithSilver(data: any, helpers: any) {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      if (!helpers.selectedCharacterId) {
        await queryRunner.rollbackTransaction();
        return { act_id: 1302, code: -1, msg: "请先选择角色" };
      }

      const { id, type = 0 } = data;

      if (!id) {
        await queryRunner.rollbackTransaction();
        return { act_id: 1302, code: -1, msg: "装备ID不能为空" };
      }

      // 1. 从equipment_base表查询装备信息
      const equipmentBase = await this.equipmentBaseService.getEquipmentById(
        id
      );
      if (!equipmentBase) {
        await queryRunner.rollbackTransaction();
        return { act_id: 1302, code: -1, msg: "装备不存在" };
      }

      // 2. 检查角色是否存在
      const character = await this.characterService.getCharacterById(
        helpers.selectedCharacterId
      );
      if (!character) {
        await queryRunner.rollbackTransaction();
        return { act_id: 1302, code: -1, msg: "角色不存在" };
      }

      // 3. 获取角色资源信息
      const characterResources = await queryRunner.manager.findOne(
        CharacterResourcesEntity,
        {
          where: { characterId: helpers.selectedCharacterId },
        }
      );
      if (!characterResources) {
        await queryRunner.rollbackTransaction();
        return { act_id: 1302, code: -1, msg: "角色资源信息不存在" };
      }

      // 4. 检查银币是否足够
      const price = Number(equipmentBase.price) || 0;
      const currentSilver = Number(characterResources.silver);
      if (currentSilver < price) {
        await queryRunner.rollbackTransaction();
        return { act_id: 1302, code: -1, msg: "银币不足" };
      }

      // 5. 扣除银币
      await queryRunner.manager.update(
        CharacterResourcesEntity,
        { characterId: helpers.selectedCharacterId },
        {
          silver: currentSilver - price,
          updated_at: new Date(),
        }
      );

      // 6. 添加装备到角色装备背包
      await this.characterEquipmentInventoryService.addEquipmentToInventory(
        helpers.selectedCharacterId,
        id,
        1
      );

      // 提交事务
      await queryRunner.commitTransaction();

      return {
        act_id: 1302,
        code: 0,
        msg: `成功以${price}银币购买了1个${equipmentBase.name}`,
      };
    } catch (error: any) {
      await queryRunner.rollbackTransaction();
      console.error("银币购买装备失败:", error);

      // 根据错误类型返回不同的错误码
      if (error.message.includes("银币不足")) {
        return { act_id: 1302, code: -1, msg: "银币不足" };
      } else if (error.message.includes("装备不存在")) {
        return { act_id: 1302, code: -1, msg: "装备不存在" };
      } else if (error.message.includes("角色不存在")) {
        return { act_id: 1302, code: -1, msg: "角色不存在" };
      }

      return {
        act_id: 1302,
        code: -1,
        msg: error?.message || "购买装备失败",
      };
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 装备洗孔 (1094)
   * 指令格式: {c: 1094, d: {id: 装备ID, i: 槽位位置}}
   */
  async handleWashSocket(data: any, helpers: any) {
    try {
      const { id: equipmentId, i: socketSlot } = data;
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 1094,
          code: -1,
          msg: "请先选择角色",
        };
      }

      if (!equipmentId || !socketSlot) {
        return {
          act_id: 1094,
          code: -1,
          msg: "参数错误：装备ID和槽位位置不能为空",
        };
      }

      if (socketSlot < 1 || socketSlot > 3) {
        return {
          act_id: 1094,
          code: -1,
          msg: "槽位位置错误：必须是1、2或3",
        };
      }

      // 调用宝石服务的洗孔方法
      const result = await this.gemService.washSocket(
        characterId,
        equipmentId,
        socketSlot
      );

      if (result.success) {
        return {
          act_id: 1094,
          code: 0,
          msg: result.message,
        };
      } else {
        return {
          act_id: 1094,
          code: -1,
          msg: result.message,
        };
      }
    } catch (error: any) {
      console.error("处理装备洗孔指令1094失败:", error);
      return {
        act_id: 1094,
        code: -1,
        msg: error?.message || "洗孔失败",
      };
    }
  }
}
